package com.atguigu.juc.day03.jmm;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo02AtomicClass {

    // 使用原子类创建数值数据
    private AtomicInteger number = new AtomicInteger(0);

    public void doAdd() {
        number.incrementAndGet();
    }

    public int getNumber() {
        return number.intValue();
    }

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(2);

        Demo02AtomicClass demo = new Demo02AtomicClass();

        new Thread(()->{
            long beginTime = System.currentTimeMillis();
            for (int i = 0; i < 10000000; i++) {
                demo.doAdd();
            }
            long endTime = System.currentTimeMillis();
            long usedTime = endTime - beginTime;
            System.out.println("usedTime = " + usedTime + "ms");
            countDownLatch.countDown();
        }, "thread-a").start();

        new Thread(()->{
            long beginTime = System.currentTimeMillis();
            for (int i = 0; i < 10000000; i++) {
                demo.doAdd();
            }
            long endTime = System.currentTimeMillis();
            long usedTime = endTime - beginTime;
            System.out.println("usedTime = " + usedTime + "ms");
            countDownLatch.countDown();
        }, "thread-b").start();

        countDownLatch.await();
        int numberCurrent = demo.getNumber();
        System.out.println("numberCurrent = " + numberCurrent);
    }
}
